package com.proton.carepatchtemp.login.activity;

import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.apkfuns.logutils.LogUtils;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.proton.carepatchtemp.BuildConfig;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.activity.LoginInternationalActivity;
import com.proton.carepatchtemp.activity.MainActivity;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.table.FestivalSplash;
import com.proton.carepatchtemp.service.AliyunService;
import com.proton.carepatchtemp.utils.AppUtils;
import com.proton.carepatchtemp.utils.FileUtils;
import com.proton.carepatchtemp.utils.PermissionUtils;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.ReportCenter;
import com.proton.carepatchtemp.utils.net.SignCenter;
import com.sdsmdg.tastytoast.TastyToast;
import com.sinping.iosdialog.animation.BaseAnimatorSet;
import com.sinping.iosdialog.animation.BounceEnter.BounceTopEnter;
import com.sinping.iosdialog.animation.SlideExit.SlideBottomExit;
import com.sinping.iosdialog.dialog.listener.OnBtnClickL;
import com.sinping.iosdialog.dialog.widget.NormalDialog;
import com.taobao.sophix.SophixManager;

import java.io.File;

public class WelcomeActivity extends BaseActivity {

    ControllerListener controllerListener;
    private BaseAnimatorSet bas_in;
    private BaseAnimatorSet bas_out;
    private boolean isNeedUpdate = false;
    private SimpleDraweeView mSDVFestivalImg;
    private LinearLayout mLnlWelcome;
    private PermissionUtils.PermissionGrant mPermissionGrant = requestCode -> {
        switch (requestCode) {
            case PermissionUtils.CODE_RECORD_AUDIO:
                TastyUtils.makeTextShort("Result Permission Grant CODE_RECORD_AUDIO", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_GET_ACCOUNTS:
                TastyUtils.makeTextShort("Result Permission Grant CODE_GET_ACCOUNTS", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_READ_PHONE_STATE:
                TastyUtils.makeTextShort("Result Permission Grant CODE_READ_PHONE_STATE", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_CALL_PHONE:
                TastyUtils.makeTextShort("Result Permission Grant CODE_CALL_PHONE", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_CAMERA:
                TastyUtils.makeTextShort("Result Permission Grant CODE_CAMERA", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_ACCESS_FINE_LOCATION:
                TastyUtils.makeTextShort("Result Permission Grant CODE_ACCESS_FINE_LOCATION", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_ACCESS_COARSE_LOCATION:
                TastyUtils.makeTextShort("Result Permission Grant CODE_ACCESS_COARSE_LOCATION", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                TastyUtils.makeTextShort("Result Permission Grant CODE_READ_EXTERNAL_STORAGE", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
                TastyUtils.makeTextShort("Result Permission Grant CODE_WRITE_EXTERNAL_STORAGE", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_SYSTEM_ALERT_WINDOW:
                TastyUtils.makeTextShort("Result Permission Grant CODE_SYSTEM_ALERT_WINDOW", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_MULTI_PERMISSION:
                break;
            default:
                break;
        }
    };

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            case Codes.NET_GET_SPLASH_PIC:
                FestivalSplash festivalSplash = (FestivalSplash) event.getObj();
                LogUtils.d(festivalSplash);
                if (!TextUtils.isEmpty(festivalSplash.getOssAddress())) {
                    DraweeController controller = Fresco.newDraweeControllerBuilder()
                            .setControllerListener(controllerListener)
                            .setUri(festivalSplash.getOssAddress())
                            // other setters
                            .build();
                    mSDVFestivalImg.setVisibility(View.VISIBLE);
                    mLnlWelcome.setVisibility(View.INVISIBLE);
                    mSDVFestivalImg.setController(controller);
                }
                if (AppUtils.needUpdate(festivalSplash.getAndroidVersion())) {
                    isNeedUpdate = true;
                    updateApp();
                }
                break;
        }
    }

    private void updateApp() {
        final NormalDialog dialog = new NormalDialog(WelcomeActivity.this);
        dialog.setCanceledOnTouchOutside(false);
        dialog.content("发现新版本，请点击确认更新！")//
                .btnNum(1)
                .btnText("立即体验！")//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();

        dialog.setOnBtnClickL((OnBtnClickL) () -> {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(AppUtils.DOWN_LOAD_ADDRESS_TENCENT);
            intent.setData(content_url);
            startActivity(intent);
            dialog.dismiss();
        });
    }

    @Override
    public void setListener() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        setContentView(R.layout.activity_welcome);
        initView();

        bas_in = new BounceTopEnter();
        bas_out = new SlideBottomExit();

        initFrescoController();

        File file0 = new File(FileUtils.getDataCache());
        if (!file0.exists()) {
            file0.mkdirs();
        }
        FileUtils.deleteFolderFile(FileUtils.getDataCache(), false);
        if (!BuildConfig.DEBUG) {
            SophixManager.getInstance().queryAndLoadNewPatch();
        }

        startService(new Intent(this, AliyunService.class));
        login();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedUpdate) {
            updateApp();
        }
    }

    private void initFrescoController() {
        controllerListener = new BaseControllerListener<ImageInfo>() {
            @Override
            public void onFinalImageSet(
                    String id,
                    @Nullable ImageInfo imageInfo,
                    @Nullable Animatable anim) {
                if (imageInfo == null) {
                    LogUtils.d("imageInfo == null");
                    return;
                }
            }

            @Override
            public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) {
                LogUtils.d("Intermediate image received");
            }

            @Override
            public void onFailure(String id, Throwable throwable) {
                LogUtils.e("onFailure String id = " + id);
                LogUtils.e(throwable);
            }
        };
    }

    @Override
    protected void onStart() {
        super.onStart();
        PermissionUtils.requestMultiPermissions(this, mPermissionGrant);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealEvent(event);
    }

    private void initView() {
        mSDVFestivalImg = findViewById(R.id.sdv_festival_img);
        mLnlWelcome = findViewById(R.id.lnl_welcome);
        ReportCenter.getAliyunToken();
    }

    private void login() {
        LogUtils.e("login....");
        if (SpUtils.getBoolean(Extras.FIRST_START_APP, true)) {
            Intent intent1 = new Intent(WelcomeActivity.this, FirstStartActivity.class);
            startActivity(intent1);
            SpUtils.saveBoolean(Extras.FIRST_START_APP, false);
            finish();
            return;
        }

        if (TextUtils.isEmpty(VCare.get().getToken()) || VCare.get().getUid() == 0) {
            if (VCare.isInternal) {
                jumpToActivty(LoginInternationalActivity.class);
            } else {
                jumpToActivty(LoginFirstActivity.class);
            }
            finish();
            return;
        }

        SignCenter.getSplashPic();
        startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        finish();
    }
}
